import React, { useRef, useState, useEffect } from 'react';
import { Base } from '../base';
import { useStep } from 'use/step';
import { useScan } from 'use/scan';
import { get_path, StepDes } from 'base/ctl/base';
import { MainMenu } from 'base/ctl/menu';
import { Time } from 'base/ctl/base';
import { Title } from 'base/ctl/title';
import { DlgLog } from 'base/ctl/log';
import { g_psn, g_db, g_wsn } from 'db/state';
import { urlTb, obj_float, Wait, ck_float, useForm, IkInput, NuiBt, useHigh } from 'sui';
import { loc } from 'local/index.js';
import { clear_info } from 'use/info';
import { NumBoard } from 'base/ctl/keyboard';
import { DlgInput } from '../sort/ctl/ctl';
import { DlgTech } from './ctl';

const fix_esop = () => {
    return [
        {stepcode: 104, stepdes: <div>扫描<span className="text-red-600">外圈</span>轴承码</div>},
        {stepcode: 3, stepdes: <div>填写测量数据</div>},
    ];
};

const FormView = ({ form, value, setValue }) => {
    const [cur, setCur] = useState();
    const [select, setSelect] = useState(true);
    const kia_ref = useRef(null);
    const sia_ref = useRef(null);
    const kea_ref = useRef(null);
    const sea_ref = useRef(null);
    const weigh_ref = useRef(null);

    useEffect(() => {
        const v = cur;

        if (!v && kia_ref.current) {
            kia_ref.current.focus();
            if (select) {
                kia_ref.current.select();
            }
        } else if (v === "kia" && sia_ref.current) {
            sia_ref.current.focus();
            if (select) {
                sia_ref.current.select();
            }
        } else if (v === "sia" && kea_ref.current) {
            kea_ref.current.focus();
            if (select) {
                kea_ref.current.select();
            }
        } else if (v === "kea" && sea_ref.current) {
            sea_ref.current.focus();
            if (select) {
                sea_ref.current.select();
            }
        } else if (v === "sea" && weigh_ref.current) {
            weigh_ref.current.focus();
            if (select) {
                weigh_ref.current.select();
            }
        } else if (v === "weigh" && kia_ref.current) {
            kia_ref.current.focus();
            if (select) {
                kia_ref.current.select();
            }
        }
    }, [cur, select]);

    const lst = [
        {ref: kia_ref, k: "kia"},
        {ref: sia_ref, k: "sia"},
        {ref: kea_ref, k: "kea"},
        {ref: sea_ref, k: "sea"},
        {ref: weigh_ref, k: "weigh"},
    ];

    const hkey = (k, v) => {
        if (k !== "Enter") {
            setSelect(false);
            return;
        }

        setCur(v);
        setSelect(true);
    };

    return (
        <div className="flex flex-col">
            <div className="inline-flex items-center justify-center">
                <div className="bg-white flex flex-col mt-2 ml-4">
                    <div className="bg-orange-700 pl-4 text-2xl text-white">内圈</div>
                    <div className="inline-flex">
                        <IkInput label="内圈径向跳动" value={value} form={form} name="kia" href={kia_ref} className="ml-6 mb-2"
                        hkey={k => hkey(k, "kia")}/>
                        <IkInput label="内圈轴向跳动" value={value} form={form} name="sia" href={sia_ref} className="mx-6 mb-2"
                        hkey={k => hkey(k, "sia")}/>
                    </div>
                </div>
                <div className="bg-white flex flex-col ml-6 mt-2">
                    <div className="bg-green-700 pl-4 text-2xl text-white">外圈</div>
                    <div className="inline-flex">
                        <IkInput label="外圈径向跳动" value={value} form={form} name="kea" href={kea_ref} className="ml-6 mb-2"
                        hkey={k => hkey(k, "kea")}/>
                        <IkInput label="外圈轴向跳动" value={value} form={form} name="sea" href={sea_ref} className="mx-6 mb-2"
                        hkey={k => hkey(k, "sea")}/>
                    </div>
                </div>
                <div className="bg-white flex flex-col ml-6 mt-2">
                    <div className="bg-blue-700 pl-4 text-2xl text-white">称重</div>
                    <IkInput label="重量" value={value} form={form} name="weigh" href={weigh_ref} className="mx-6 mb-2"
                    hkey={k => hkey(k, "weigh")}/>
                </div>
            </div>
            <NumBoard className="mt-12 flex justify-center" lst={lst} value={value} setValue={setValue}/>
        </div>
    );
};

const ClientView = ({ umd, wsn }) => {
    const [open_input, openInput] = useState(false);
    const [open_tech, openTech] = useState(false);
    const [open_menu, openMenu] = useState(false);
    const [open_log, openLog] = useState(false);
    const [wait, setWait] = useState(false);
    const [high] = useHigh(10, 200)
    const [value, setValue] = useState();
    const form = useForm(setValue);

    useScan(wsn, umd);

    useEffect(() => {
        if (!wsn) {
            return;
        }

        umd.setEsop(fix_esop());
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [wsn]);

    const hfin = () => {
        const ck = {
            "kia": (v) => ck_float(v),
            "sia": (v) => ck_float(v),
            "kea": (v) => ck_float(v),
            "sea": (v) => ck_float(v),
            "weigh": (v) => {
                const e = ck_float(v);
                if (e) {
                    return e;
                }

                const tmp = parseFloat(v);
                if (tmp <= 0.0000001) {
                    return "重量不能小于0";
                }

                return null;
            }
        };

        if (!form.hcheck(ck, value)) {
            return;
        }

        const tech_sn = umd.get("tech");
        if (!tech_sn) {
            umd.setErr("型号不能为空");
            return;
        }

        setWait(true);

        const cmd = {
            "tab": "rotate",
            "line": "1",
            "data": [
                {
                    "psn": g_psn(),
                    "wsn": g_wsn(),
                    "k": {
                        "usn": "test",
                        "tsn": g_db.tech(),
                        "sn": g_db.task(),
                    },
                    "v": {
                        "uname": "test",
                        "kia": obj_float(value, "kia"),
                        "sia": obj_float(value, "sia"),
                        "kea": obj_float(value, "kea"),
                        "sea": obj_float(value, "sea"),
                        "weigh": obj_float(value, "weigh"),
                    }
                },
            ]
        };

        urlTb(null, "chunk", cmd,
            r => {
                setWait(false);

                const tech_sn = g_db.tech();

                umd.clear();
                clear_info();

                g_db.s_tech(tech_sn);

                umd.mset({
                    "tech": tech_sn,
                });
            },
            e => {
                setWait(false);
                umd.setErr("数据提交失败，请重试");
            });
    };

    const menu = [{
        label: "重新开始",
        name: "clear",
        hcmd: () => {
            umd.clear();
            clear_info();
        }
    }, {
        label: "设置型号",
        name: "tech",
        hcmd: () => openTech(true),
    }, {
        label: "输入条码",
        name: "input",
        hcmd: () => openInput(true),
    }, {
        label: loc("base_157"),
        name: "log",
        hcmd: () => openLog(true),
    }];

    const is_dis = () => {
        const st = umd.get("state");
        if (st === "hand") {
            return false;
        }

        return true;
    };

    const getView = () => {
        const st = umd.get("state");
        if (st !== "hand") {
            return null;
        }

        return <FormView form={form} value={value} setValue={setValue}/>;
    };

    return (
        <div className="flex flex-col ml-2 mr-1">
            <div className="inline-flex mt-2 justify-between">
                <div className="inline-flex">
                    <div className="ml-2 mr-4">
                        <MainMenu value={menu} open={open_menu} setOpen={openMenu}/>
                    </div>
                    <Title value="旋转精度测量" sub={g_wsn()} width="w-56"/>
                    <Title value={umd.get("task")} sub="工单号" width="w-56"/>
                    <Title value={umd.get("tech")} sub="型号" width="w-56"/>
                    <Title value={umd.get("psn")} sub="外圈轴承码" width="w-64"/>
                </div>
            </div>
            <div className="flex flex-row items-start mt-1">
                <div className="flex flex-col w-full">
                    <div className="inline-flex justify-between my-4 mr-1">
                        <StepDes umd={umd}/>
                        <NuiBt color="green" className="mt-1 ml-4 w-px-next" hcmd={hfin} disabled={is_dis()}>
                            <div className="text-2xl">提交数据</div>
                        </NuiBt>
                    </div>
                    <div style={{ height: `${high - 310}px`, width: "100%" }} className="my-1 border">
                        {getView()}
                    </div>
                </div>
            </div>
            <div className="inline-flex items-center justify-between">
                <div className="w-full mr-2 mt-2 border border-white rounded bg-white justify-between">
                    <div className="ml-2 font-bold text-xl text-red-600 h-12">{umd.get("err")}</div>
                </div>
                <div className="flex justify-center ml-2 w-32">
                    <Time up={true}/>
                </div>
            </div>
            <DlgLog open={open_log} setOpen={openLog}/>
            <Wait wait={wait}/>
            <DlgInput open={open_input} setOpen={openInput}/>
            <DlgTech open={open_tech} setOpen={openTech} umd={umd}/>
        </div>
    );
};

const RotateClient = ({ pathname, mod }) => {
    const [line, wsn] = get_path(pathname, mod);
    const umd = useStep(line, wsn);

    if (g_db.is_stop_scan()) {
        g_db.start_scan();
    }

    return (
        <Base wsn={wsn} line={line}>
            <ClientView umd={umd} wsn={wsn}/>
        </Base>
    );
};

export {RotateClient};
